const path = require('path');
const fs = require('fs');
let pagePath = path.resolve(process.cwd(), 'src/page/');
function main() {
  let existPath = fs.existsSync(pagePath);
  if (!existPath) {
    return console.log('目录错误：' + pagePath);
  }
  let fileList = [];
  let dictList = fs.readdirSync(pagePath);
  for (let one of dictList) {
    let onePath = path.resolve(pagePath, one);
    if (!one.includes('.')) {
      let oneList = fs.readdirSync(onePath);
      for (let two of oneList) {
        let twoPath = path.resolve(onePath, two);
        if (!two.includes('.')) {
          let twoList = fs.readdirSync(twoPath);
          for (let three of twoList) {
            let threePath = path.resolve(twoPath, three);
            if (!three.includes('.')) {
              let threeList = fs.readdirSync(threePath);
              for (let four of threeList) {
                let fourPath = path.resolve(threePath, four);
                if (four.includes('.') && readRoute(four, fourPath)) {
                  fileList.push(fourPath);
                }
              }
            } else if (readRoute(three, threePath)) {
              fileList.push(threePath);
            }
          }
        } else if (readRoute(two, twoPath)) {
          fileList.push(twoPath);
        }
      }
    } else if (readRoute(one, onePath)) {
      fileList.push(onePath);
    }
  }
  let importList = [
    `import { MenuTypes } from './components/mainNavBar';`,
    `import NotFoundPage from '@src/page/NotFoundPage';`,
  ];
  let lineList = [];
  for (let _path of fileList) {
    let _isPage = isPage(_path);
    if (!_isPage) {
      continue;
    }
    let usePath = ('@src' + _path.replaceAll('\\', '/').split('src')[1]).split('.')[0];
    let fileName = usePath.split('/').pop();
    fileName = fileName.substring(0, 1).toUpperCase() + fileName.substring(1).split('.')[0];
    importList.push(`import ${fileName} from '${usePath}';`);
    let routePath = usePath.split('page')[1].split('/');
    routePath.pop();
    let pageType = fileName.includes('ListPage') ? 'index' : 'detail';
    lineList.push(
      `'${routePath.join('/').toLowerCase()}/${pageType}': (arg) => <${fileName} currentRouteRecord={arg!} />,`
    );
  }
  lineList = importList.concat(
    [
      '// 页面配置',
      '// 列表或基本页面用 routedata.path/children.path/index 后面跟index',
      '// 详情页面 用  routedata.path/children.path/detail 后面跟detail',
      'const componentsMap: { [x: string]: (arg?: MenuTypes) => JSX.Element } = {',
    ],
    lineList,
    ['any: () => <NotFoundPage loading={false} />,', '};', 'export default componentsMap;']
  );
  let routeFile = path.resolve(process.cwd(), 'src', 'router.tsx');
  fs.writeFileSync(routeFile, lineList.join('\n'));
}

function isPage(_path) {
  if (fs.existsSync(_path)) {
    let content = fs.readFileSync(_path);
    if (content.includes('currentRouteRecord: MenuTypes;')) {
      return true;
    }
  }
  return false;
}

function readRoute(fileName, path) {
  if (fileName.includes('.tsx')) {
    // console.log('find path :', path);
    return true;
  }
  return false;
}

module.exports = main;
